import { request } from '@/zero';

/**
 * 命名空间
 */
const namespace = 'task-list';

/**
 * 初始结构
 */
const initialState = {
  dataSource: [], // 数据源
  total: 0, // 数据总量

  pagination: {
    current: 1,
    pageSize: 10,
  }, // 分页

  filters: {}, // 过滤
  sorter: {}, // 排序
  searcher: {}, // 搜索
};

/**
 * 定义model
 */
export default {
  namespace, // namespace: namespace

  state: initialState,

  effects: {
    *fnCreate({ payload }, { call, put, select }) {
      const response = yield call(request, `/api/${namespace}s`, {
        method: 'post',
        body: payload,
      });
      const newPagination = yield select(models => {
        const { pagination } = models[namespace];
        return { ...pagination, current: 1 };
      });
      yield put({ type: `fnList`, payload: { pagination: newPagination } });
      return response;
    },

    *fnList({ payload }, { call, put, select }) {
      const newRules = yield select(models => {
        const { pagination, filters, sorter, searcher } = models[namespace];
        return {
          pagination,
          filters,
          sorter,
          searcher,
          ...payload,
        };
      });
      const { pagination, filters, sorter, searcher } = newRules;
      const response = yield call(request, `/api/${namespace}s`, {
        method: 'get',
        body: { ...pagination, ...filters, ...sorter, ...searcher },
      });
      yield put({ type: 'save', payload: { ...response.data, ...newRules } });
    },

    *fnUpdate({ payload }, { call, put }) {
      const response = yield call(request, `/api/${namespace}s/${payload.id}`, {
        method: 'put',
        body: payload,
      });
      yield put({ type: `fnList` });
      return response;
    },

    *fnDelete({ payload }, { call, put, select }) {
      const response = yield call(request, `/api/${namespace}s/${payload.id}`, {
        method: 'delete',
        body: {
          id: payload.id,
        },
      });
      if (response.success) {
        const newPagination = yield select(models => {
          const { pagination } = models[namespace];
          const { current, pageSize, total } = pagination;
          const offset = (current - 1) * pageSize;
          return { ...pagination, current: offset && offset === total - 1 ? current - 1 : current };
        });
        yield put({ type: `fnList`, payload: { pagination: newPagination } });
      }
      return response;
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
  },
};
